package com.baihui.crm.export;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.baihui.crm.BaihuiSession;
import com.baihui.crm.util.BaihuiOptUtil;
import com.baihui.crm.util.ExportUtil;
import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.CommonDAO;
import com.baihui.taobao.db.GeneDAO;
import com.baihui.taobao.db.OrderDAO;
import com.baihui.taobao.db.TradeDAO;
import com.baihui.taobao.transition.IViewProgressSupport;
import com.taobao.api.domain.Sku;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 12-1-27 Time: 下午9:11
 * 导入订单时要求Product Id必须存在，否则不能导入.
 */
public class ExportOrder extends ExportData implements IViewProgressSupport {

	public ExportOrder(BaihuiSession baihuiSession,
			TaoBaoSessionInfo taoBaoSessionInfo) {
		super(baihuiSession, taoBaoSessionInfo);
	}

	@Override
	public GeneDAO getDomainDAO() {
		return new OrderDAO();
	}

	public void exportOrder(Long userid) throws Exception {
		// logger.info("开始导入ORDER到百会CRM.");
		exportData(Orders, userid);
		// logger.info("结束导入ORDER到百会CRM.");
		markImportProgress(98);
	}

	/**
	 * 库存信息需要即时查询，因此在导出数据时来更新.
	 * 
	 * @param allData
	 * @param type
	 * @param userid
	 * @return
	 */
	protected List<Map> constructureData(List<Map> allData, String type,
			Long userid) throws Exception {
		if (allData == null || allData.size() <= 0)
			return allData;

		// ItemDao itemDao = new ItemDao();
		TradeDAO tradeDAO = new TradeDAO();
		// List<Map> titemList = itemDao
		// .findAllObject("select * from titem where userid = ?",
		// new Object[] { userid });
		// Map titemMap = new HashMap();
		// for (Map map : titemList) {
		// titemMap.put(map.get("num_iid"), map);
		// }
		for (Map trade : allData) {

			Map shoppingMap = tradeDAO
					.findDate(
							" select type,companyName,outSid from tbshipping where tid= ?  ",
							new Object[] { trade.get("tid") });

			List<Map> orderList = tradeDAO
					.findAllObject(
							"select tm.baihuiid,tm.title,tb.num,tb.price,tb.discountFee,tb.payment,tb.skuPropertiesName from tborder tb left join titem tm on tb.numIid = tm.num_iid where tb.userId = ? and tb.parent = ? ",
							new Object[] { userid, trade.get("tid") });
			// Map tradeMap = new HashMap();
			trade.put(("shipping"), shoppingMap);
			trade.put(("orders"), orderList);
			trade.put("sku", new Sku());
		}

		// for (Map order : allData) {
		// long start = System.currentTimeMillis();
		// if (order.get("numIid") != null) {
		// if (titemMap.get(order.get("numIid")) != null) {
		// order.put("item", titemMap.get(order.get("numIid")));
		// } else {
		// order.put("item", new HashMap<String, Object>());
		// }
		// }
		//
		// if (order.get("parent") != null) {
		// if (tradeMap.get(order.get("parent")) != null) {
		// order.put("trade", tradeMap.get(order.get("parent")));
		// } else {
		// Map map = new HashMap();
		// map.put("shipping", new HashMap<String, Object>());
		// order.put("trade", map);
		// }
		// }
		// order.put("sku", new Sku());
		// }
		return allData;
	}

	// TODO: 在上面的处理的中已经将下架的商品的订单置成了-1，这就不需要处理了。 2012-04-14
	// @Override
	// protected String getSql(String type, Long userid, Timestamp
	// lastExportTime,
	// int lotNo) {
	// if (Orders.equals(type)) {
	// return "select * from tborder where lotNo="
	// + lotNo
	// +
	// " and (exported = 0 or exported is null) and numIid in (select num_iid from titem where baihuiid is not null and userid='"
	// + userid + "') and userId=" + userid + " ";
	// } else {
	// return super.getSql(type, userid, lastExportTime, lotNo);
	// }
	// }

	@Override
	public String[] getEntryKeys() {
		return new String[] { "Product@Details" };
	}

	@Override
	/**
	 * keys为在.properties中配置的分录的属性.
	 */
	protected String constructureEntryXMLString(List keys, Map source,
			String entryKey) throws Exception {
		if (keys == null || keys.size() <= 0)
			return null;
		StringBuilder sb = new StringBuilder();
		sb.append("<FL val=\"" + (getKey(entryKey)) + "\">");
		List<Map> orders = (List<Map>) source.get("orders");
		int rows = 1;
		// 小计
		double total = 0.0;
		// 折扣
		double discount = 0.0;
		// 累计
		double grandTotal = 0.0;
		for (Map order : orders) {
			sb.append("<product no=\"" + rows + "\">");
			for (Object key : keys) {
				String valueKey = loader.getProperty((String) key);
				String tmp = key.toString().replace(entryKey + ".", "");
				if (tmp == null || tmp.equals(""))
					continue;
				Object value = getValue(valueKey, order);
				value = format(value, tmp);
				sb.append("<FL val=\"" + getKey(tmp) + "\">" + value + "</FL>");
			}
			sb.append("</product>");
			total = total
					+ ExportUtil.getAfterTotal(
							BigDecimal.valueOf(Double.valueOf(String
									.valueOf(order.get("price")))),
							Long.valueOf(String.valueOf(order.get("num"))),
							BigDecimal.valueOf(Double.valueOf(String
									.valueOf(order.get("discountFee")))))
							.doubleValue();
			rows++;
		}
		sb.append("</FL>");
		sb.append("<FL val='Sub Total'>" + total);
		sb.append("</FL>");
		// sb.append("<FL val='Discount'>" + discount);
		// sb.append("</FL>");
		// sb.append("<FL val='Grand Total'>" + grandTotal);
		// sb.append("</FL>");
		return sb.toString();
	}

	public void markImportProgress(int progress) {
		// System.out.println("当前进度：" + progress + "%");
		taobaosession.setOrderImportProgress(progress);
	}

	public int viewImportProgress() {
		return taobaosession.getOrderImportProgress();
	}

	@Override
	protected void afterExported(String type, Long userid) throws Exception {
		// 更新宝贝的累计销量
		String sql = "select * from titem where exported = 2 and userId= ? ";
		CommonDAO dao = new CommonDAO();
		List<Map> updateItem = dao.findAllObject(sql, new Object[] { userid });

		afterExportUpdateProduct(dao, updateItem);

		// 更新订单信息
		String sqlOrder = "select * from tborder where exported = 2 and userId= ? ";
		List<Map> updateOrder = dao.findAllObject(sqlOrder,
				new Object[] { userid });
		updateOrder = constructureData(updateOrder, type, userid);

		afterExportUpdateOrder(type, dao, updateOrder);
		markImportProgress(85);
	}

	private void afterExportUpdateOrder(String type, CommonDAO dao,
			List<Map> updateOrder) throws Exception {
		try {
			for (Map order : updateOrder) {
				if (!order.isEmpty()) {
					if (order.get("baihuiid") == null) {
						continue;
					}
					StringBuilder stringBuilder = new StringBuilder();
					// 批量形成数据.
					stringBuilder.append("<" + Orders + ">");
					// 根据配置得到百会字段与淘宝字段的映射
					String xmlDataString = populate(order, type, 1);
					// 调用导出数据，返回是否导出成功.
					if (xmlDataString == null) {
						logger.info("获取的XMLString为空！");
						continue;
					}
					stringBuilder.append(xmlDataString);
					stringBuilder.append("</" + type + ">");

					String result = null;
					result = BaihuiOptUtil.updateRecord(baihuiSession, type,
							stringBuilder.toString(),
							String.valueOf(order.get("baihuiid")));

					String updateSql = "update tborder set exported = 1 where baihuiid = ? ";
					dao.updateAndInsert(updateSql,
							new Object[] { order.get("baihuiid") });

				}
			}
		} catch (Exception ex) {
			throw ex;
		}

	}

	private void afterExportUpdateProduct(CommonDAO dao, List<Map> updateItem)
			throws Exception {

		try {
			// 更新百会商品数据
			for (Map item : updateItem) {
				if (!item.isEmpty()) {
					if (item.get("baihuiid") == null) {
						continue;
					}
					StringBuilder xmlDataString = new StringBuilder();
					xmlDataString.append("<Products>");
					xmlDataString.append("<row no=\"1\">");
					xmlDataString.append("<FL val=\"" + "累计销量" + "\">"
							+ item.get("increamnum") + "</FL>");
					xmlDataString.append("</row>");
					xmlDataString.append("</Products>");
					// System.out.println("更新商品数量:"+xmlDataString);
					String result = BaihuiOptUtil.updateRecord(baihuiSession,
							Products, xmlDataString.toString(),
							item.get("baihuiid").toString());

					String updateSql = "update titem set exported = 1 where baihuiid = ? ";
					dao.updateAndInsert(updateSql,
							new Object[] { item.get("baihuiid") });
				}
			}
		} catch (Exception ex) {
			throw ex;
		}
	}
}
